package business.database.sqliteMaescorp


import groovy.sql.Sql
import java.util.HashMap;
import java.util.List;

/**
 * DAO para la tabla Word${centerCOL}
 * @author Administrador
 *
 */
public abstract class AbsWordStatisticDAO<E> {
	
	protected def Sql sqlite;
	
	protected String centerCOL;
	
	/**
	 * Inicializamos la clase con la instance de SQL
	 * @param sql
	 */
	public AbsWordStatisticDAO(Sql sql,String col) {
		sqlite = sql;
		centerCOL = col;
	}
	
/**
 * Crea la tabla
 */
	public void create() {
		String sql = "CREATE TABLE IF NOT EXISTS Word${centerCOL} (word text COLLATE NOCASE primary key, ${centerCOL} text COLLATE NOCASE, per double, cnt integer);";
		sqlite.execute(sql);
			
	}
	
	/**
	 * @return si ya existe la palabra
	 */
	public boolean exists(String word) {
		String sqlQuery = "Select * from Word${centerCOL} where word = ?"
		def max = sqlite.firstRow(sqlQuery,[word])
					
		if ((max != null) && (max[0] != null))
			return true;
		else return false;
	}
	
	/**
	 * Inserta una palabra
	 */
	public void insert(String word, String centerCol, Double per, Integer cnt) {
		String sql = "insert into Word${centerCOL} values (?,?,${per},${cnt})";
		sqlite.execute(sql, [word, centerCol]);
	}
	
	/**
	 * Actualiza las estadisticas de una palabra
	 * @param word
	 * @param org
	 * @param per
	 * @param cnt
	 */
	public void update(String word, String centerCol, Double per, Integer cnt) {
		String sql = "update Word${centerCOL} set ${centerCOL} = ?, per = ${per}, cnt = ${cnt} where word = ?";
		sqlite.execute(sql, [centerCol,word]);
	}
	/**
	 * Itera sobre todas las palabras
	 * @param closure
	 */
	public void iterateOverWords(Closure closure) {
		String sql = "select word from Word${centerCOL}"
	   sqlite.eachRow(sql, closure);
	}
	
   
	abstract public E select(String word);
	
	
	
}
